/**
 * unPlarer-Youtube 0.8.0 
 *
 * @author Alvaro Lopez, Juan Baquero
 * 
 * http://code.google.com/p/unplayer-youtube/
 **/

package unplayer.youtubeplayer;

import processing.core.PApplet;
import unplayer.videoplayer.VideoPlayer;
import unplayer.youtubeplayer.util.UrlStream;

public class VideoPlayerYoutube extends VideoPlayer{

	public VideoPlayerYoutube(PApplet pa) {
		super(pa);
		setupNoStream();
		parent.registerDispose(this);
	}
	
	public VideoPlayerYoutube(PApplet pa, String url) {
		super(pa, null);
		setupStream(url,defaultSize);
		parent.registerDispose(this);
	}
	public VideoPlayerYoutube(PApplet pa, String url, int size) {
		super(pa, null);
		setupStream(url,size);
		parent.registerDispose(this);
	}
	
	public VideoPlayerYoutube(PApplet pa, String url,boolean title) {
		super(pa, null,title);
		setupStream(url,defaultSize);
		parent.registerDispose(this);
	}
	
	public VideoPlayerYoutube(PApplet pa, String url,boolean title, int size) {
		super(pa, null,title);
		setupStream(url,size);
		parent.registerDispose(this);
	}
	
	public void loadVideo(String video)
	{
		closeVideo();
		setupStream(video,defaultSize);
	}
	
	public void loadVideo(String video,int size)
	{
		closeVideo();
		setupStream(video,size);
	}
	
	public void setupStream(String url,int size)
	{
		util = new UrlStream();
		util.loadUrl(url, size);
		connectionState=0;               //ESTADO INICIAL "CARGANDO PAGINA DE YOUTUBE"
		contPauseYou = 0;
		setMsg("Cargando Youtube...");
		setTitle("UNPlayer  Youtube");
		super.cacheDownload(false);
	}
	
	public void setupNoStream()
	{
		connectionState=4;               //ESTADO Video sin cargar
		setMsg("");
		setTitle("UNPlayer  Youtube");
		super.cacheDownload(false);
	}
	
	public void video(int x, int y,int widthV,int heighV)
	{
		changeComand();
		super.video(x, y, widthV, heighV);
		
		
		
		if(connectionState==0)  //CARGANDO LA PAGINA
		{
			if(util.chargeg)
			{
				if(util.error==UrlStream.OK)
				{
					String stream = util.getUrlStream();
					setTitle(util.getTitle());
					setMsg("Cargando Video...");
					util.loadStream(parent, stream);
					connectionState = 1;
				}
				
				if(util.error==UrlStream.NO_CONNECTION)
				{
					setMsg("Error de Conexion...");
					connectionState = 3;
				}
				
				if(util.error==UrlStream.NO_YOUTUBE)
				{
					setMsg("No es un link valido de Youtube...");
					connectionState = 3;
				}
				
				if(util.error==UrlStream.NO_VIDEO)
				{
					setMsg("No se encontro video...");
					connectionState = 3;
				}
				
				if(util.error==UrlStream.NO_SIZE)
				{
					setTitle(util.getTitle());
					setMsg("Video no disponde en este tamanyo");
					connectionState=3;
				}
			}
		}else if(connectionState==1)  //CARGANDO EL VIDEO HASTA UN TAMANYO RASONABLE
		{
			if(util.loaded)
			{
				
				if(util.error==UrlStream.OK)
				{
					super.loadVideo(util.getFile());
					setTitle(util.getTitle());
					connectionState=2;
				}
				
				if(util.error==UrlStream.LAZY_CONNECTION)
				{
					setMsg("Conexion lenta, intente nuevamente");
					connectionState=3;
				}
				
				if(util.error==UrlStream.NO_SIZE)
				{
					setMsg("Error");
					connectionState=3;
				}
				
				if(util.error==UrlStream.NO_CONNECTION)
				{
					setMsg("Error no se puede obtener video");
					connectionState=3;
				}
			}
		}
		else if(connectionState==2)  //REPRODUCIENDO
		{
			/* La variable (lastTime) guarda el tiempo del frame anterior
			 * si el tiempo actual es menor a este valor es porque el la reproduccion
			 * alcanzo el limite que se ha descargado, con la exepcion que 
			 * halla terminado el video de reproducir (duration).
			 * 
			 * Cuando sucede esto se coloca el video en pausa en el frame que habia 
			 * quedado antes y comienza un contador "contPauseYou" que espera 100 frames
			 * (maxPauseFrames) y luego vuelve a tratar de reproducirlo
			 * */
			
			
			if(contPauseYou>0) contPauseYou++;
			
			if(contPauseYou==maxPauseFrames) 
			{
				contPauseYou=0;
				myMovie.play();
				return;
			}else if(contPauseYou>0)
			{
				return;
			}
			
			if(myMovie.time()>=myMovie.duration()-3)
			{
				lastTime=0;
				return;
			}
			
			//SI SE HA MOVIDO CON LA BARRA DE DESPLAZAMIENTO
			if(keyCommand==true && movieCommand==CM_JUMP) return;
			
			if(myMovie.time()<lastTime-2 && movieState==ST_PLAY)
			{
				 myMovie.pause();
				 myMovie.jump(lastTime); 
				 contPauseYou=1;
			}else if(movieState!=ST_PAUSE)
			{
				lastTime = myMovie.time();
			}
			
		}
	}
	
	private void changeComand() {
		if(keyCommand && 
		   (movieCommand==CM_PAUSE ||
		   movieCommand==CM_INDEX || 
		   movieCommand==CM_RESET ||
		   movieCommand==CM_STOP ||
		   movieCommand==CM_RELOAD ||
		   movieCommand==CM_JUMP)){
			lastTime =0;
		}
			
		
	}
	
	public void video(int x, int y) 
	{
		video(x, y,-1,-1);
	}
	
	public void closeVideo()
	{
		connectionState=3;
		super.closeVideo();
		if(util!=null) util.closeVideo(parent);
	}
	
	public void closePlayer()
	{
		connectionState=3;
		super.closePlayer();
		if(util!=null) util.closeVideo(parent);
		
	}
	
	public void dispose()
	{
		closePlayer();
	}
	
	private UrlStream util;
	private int connectionState;
	private float lastTime;
	private int contPauseYou;
	
	private int maxPauseFrames = 100;
	private int defaultSize = 0;
}
